package handlers

import (
	"github.com/gin-gonic/gin"
	"main/models"
	"strconv"
)

func MovieAdd(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")
	userId, _ := strconv.Atoi(c.PostForm("user_id"))

	if title == "" || content == "" || img == "" || userId == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "信息不能为空",
		})
		return
	}

	movie := models.Movie{
		Title:        title,
		Content:      content,
		Img:          img,
		UserId:       userId,
		LikeCount:    0,
		CommentCount: 0,
	}

	err := models.DB.Create(&movie).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return

}

func LikeList(c *gin.Context) {
	var movie []models.Movie
	err := models.DB.Order("like_count asc").Find(&movie).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": movie,
	})
	return
}

func CommentList(c *gin.Context) {
	var movie []models.Movie
	err := models.DB.Order("comment_count asc").Find(&movie).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": movie,
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size

	var count int64
	models.DB.Model(&models.Movie{}).Count(&count)
	var movie []models.Movie
	err := models.DB.Offset(offset).Limit(size).Find(&movie).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"count": count,
			"movie": movie,
		},
	})
	return
}
